﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Genrsis.WorkitemTracking.Commands;
using Genrsis.WorkitemTracking.Handlers;
using Genrsis.WorkitemTracking.ReadLayer;
using Genrsis.WorkitemTracking.Web.Models;
using Raven.Client;
using Genrsis.WorkitemTracking.Domain;
using System.Collections.Generic;

namespace Genrsis.WorkitemTracking.Web.Controllers
{
    public class WorkflowController : ControllerBase
    {
        private readonly ICommandProcessor _commandProcessor;

        public WorkflowController(ICommandProcessor commandProcessor, IDocumentStore documentStore)
            : base(documentStore)
        {
            _commandProcessor = commandProcessor;
        }

        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.Title = Strings.Add_new_workflow;
            ViewBag.CreateText = Strings.Create;
            ViewBag.CancelText = Strings.Cancel;

            return View();
        }

        [HttpPost]
        public ActionResult Create(WorkflowCreateViewModel model)
        {
            var userId = GetCurrentUser().Id;

            _commandProcessor.Issue(new CreateWorkflowCommand(model.Name, userId));

            return RedirectToAction("Index");
        }

    [HttpGet]
    public ActionResult Index()
    {
        ViewBag.Title = Strings.Workflows;
        ViewBag.AddNewText = Strings.Add_new;

        IEnumerable<WorkflowIndexViewModel> model;
        using (var session = DocumentStore.OpenSession())
        {
            model = session.Query<Workflow>()
                .ToArray()
                .Select(w => new WorkflowIndexViewModel { WorkflowId = w.Id, Name = w.Name });
        }

        return View(model);
    }

        [HttpGet]
        public ActionResult Show(string id)
        {
            using (var session = DocumentStore.OpenSession())
            {
                var workflow = session.Load<Workflow>(id);

                ViewBag.WorkflowName = workflow.Name;
                ViewBag.SaveText = Strings.Save;

                return View(new WorkflowShowViewModel
                                     {
                                         WorkflowId = workflow.Id,
                                         Name = workflow.Name
                                     });
            }
        }

        [HttpPost]
        public ActionResult Show(WorkflowShowViewModel model)
        {
            _commandProcessor.Issue(new EditWorkflowNameCommand { WorkflowId = model.WorkflowId, NewName = model.Name });
            return RedirectToAction("Index");
        }
    }
}
